<template>
	<div class="createPost-container">
		<el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
			<div class="createPost-main-container">
				<el-card class="box-card" id="shopInfo">
					<div slot="header" class="clearfix">
						<span>产品基本信息</span>
					</div>
					<el-form-item style="margin-bottom: 40px;" prop="name">
						<MDinput v-model="postForm.name" :maxlength="100" name="name" required>
							产品名称
						</MDinput>
					</el-form-item>
					<el-form-item label="产品主图:" prop="image" style="margin-bottom: 30px;">
						<UploadImage :image.sync="postForm.image" :limit="1" :type=1 />
						<!-- <Upload :default-image.sync="postForm.image" :mode="6" :validWidth="750" :validHeight="750" :size="1"/>
						<span style="color:#ff8704;">图片限制750*750px，大小在1M内</span> -->
					</el-form-item>
					<!-- <el-form-item label="产品轮播图:" style="margin-bottom: 30px;">
						<UpImgs :default-image.sync="images" />
					</el-form-item> -->
					<div class="postInfo-container">
						<el-form-item label="产品分类:" prop="categoryId" class="postInfo-container-item">
							<Cascader v-model="categoryId" :ids="categoryIds" ref="categoryId" placeholder="产品分类"
								:options="categoryData" :props="props" class="filter-item" />
						</el-form-item>
						<el-form-item label="单位:" prop="unit" class="postInfo-container-item">
							<el-input v-model="postForm.unit" placeholder="单位" />
						</el-form-item>
					</div>
					<!-- <div class="postInfo-container">
						<el-form-item label="发货地:" prop="city" class="postInfo-container-item">
							<AddressCascader v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
						</el-form-item>
					</div> -->
					<el-form-item prop="remark" style="margin-bottom: 30px;">
						<!-- <span style="font-size: 14px;color: #606266;">图文详情：</span> -->
						<Tinymce ref="editor" v-model="postForm.remark" :height="400" />
					</el-form-item>
				</el-card>
				<el-card class="box-card" id="biddingInfo">
					<div slot="header" class="clearfix">
						<span>竞价信息</span>
					</div>
					<div class="postInfo-container">
						<el-form-item label="起拍总价:" prop="topPrice" class="postInfo-container-item">
							<span slot="label">起拍总价<span style="font-size: 12px;color: gray">(竞拍起价必须大于竞价幅度)</span>:</span>
							<NumInput :min="1" :float="2" v-model="postForm.topPrice" />
						</el-form-item>
						<el-form-item label="竞拍数量:" prop="topNum" class="postInfo-container-item">
							<NumInput :min="1" :float="2" v-model="postForm.topNum" />
						</el-form-item>
					</div>
					<div class="postInfo-container">
						<el-form-item label="竞价类型:" class="postInfo-container-item">
              <el-input
                placeholder="请输入内容"
                v-model="userInfo.type === 1 ? '依次递减': '依次递增'"
                :readonly="true">
              </el-input>
							<!-- <el-select v-model="postForm.type" style="width:185px">
								<el-option v-for="item in typeJson" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select> -->
						</el-form-item>
						<el-form-item :label="userInfo.type === 1 ? '减价幅度/次': '加价幅度/次'" prop="topPrice"
							class="postInfo-container-item">
							<NumInput :min="1" :float="2" v-model="postForm.subPrice" />
						</el-form-item>
					</div>
					<el-form-item label="竞价时间:" prop="startDate" style="width:400px">
						<DatePicker :startDate.sync="postForm.startDate" :endDate.sync="postForm.endDate" clearable />
					</el-form-item>
				</el-card>
				<el-form-item style="margin-bottom: 30px;">
					<el-button type="primary" @click="submitForm">
						发布
					</el-button>
				</el-form-item>
			</div>
		</el-form>
		<div class="toInfo">
			<a @click.prevent="anchor('shopInfo')">产品信息</a>
			<a @click.prevent="anchor('biddingInfo')">竞价信息</a>
		</div>
	</div>
</template>
<script>
  import { mapGetters } from 'vuex'
	import Tinymce from '@/components/Tinymce'
	import Upload from '@/components/Upload'
	import UploadImage from '@/components/UploadImage'
	import UpImgs from '@/components/Upload/UpImgs'
	import MDinput from '@/components/MDinput'
	import NumInput from '@/components/NumInput'
	import Cascader from '@/components/Cascader'
	import DatePicker from '@/components/DatePicker'
	import AddressCascader from '@/components/AddressCascader'
	import {categoryPageVoByQo} from '@/api/product'
	import {biddingSave} from '@/api/transaction'

	const defaultForm = {
		name: '',
		categoryId: '',
		unit: '吨',
		startProvinceId: '',
		startProvinceName: '',
		startCityId: '',
		startCityName: '',
		startDistrictId: '',
		startDistrictName: '',
		remark: '',
		image: '',
		images: '',
		topNum: '',
		topPrice: '',
		subPrice: '',
		startDate: '',
		endDate: '',
		type: 0
	}

	export default {
		name: 'biddingBuyingSave',
		components: {
			Tinymce,
			MDinput,
			Upload,
			UpImgs,
			Cascader,
			AddressCascader,
			NumInput,
			DatePicker,
			UploadImage
		},
    computed: {
      ...mapGetters(["userInfo"]),
    },
		data() {
			const validateDate = (rule, value, callback) => {
      if (!this.postForm.startDate || !this.postForm.endDate) {
        callback(new Error('请选择时间'))
      } else if (new Date(this.postForm.startDate).getTime() < new Date().getTime()) {
        callback(new Error('起始时间必须晚于当前时间'))
      } else if(this.postForm.startDate == this.postForm.endDate) {
				callback(new Error('起始时间不能等于当前时间'))
			} else {
        callback()
      }
    }

			const validateCity = (rule, value, callback) => {
				if (!this.postForm.startDistrictId) {
					callback(new Error('请选择省市区'))
				} else {
					callback()
				}
			}
			return {
				postForm: Object.assign({}, defaultForm),
				categoryData: [],
				categoryId: '',
				categoryIds: '',
				props: {
					value: 'id',
					label: 'name'
				},
				selectedOptions: [],
				loading: false,
				userListOptions: [],
				rules: {
					image: [{required: true,message: '请选择',trigger: 'blur'}],
					categoryId: [{required: true,message: '请选择',trigger: 'blur'}],
					unit: [{required: true,message: '请输入',trigger: 'blur'}],
					name: [{required: true,message: '请输入',trigger: 'blur'}],
					remark: [{required: true,message: '请输入图文详情',trigger: 'blur'}],
					city: [{required: true,trigger: 'blur',validator: validateCity}],
					topPrice: [{required: true,message: '请输入',trigger: 'blur'}],
					topNum: [{required: true,message: '请输入',trigger: 'blur'}],
					subPrice: [{required: true,message: '请输入',trigger: 'blur'}],
					startDate: [{validator: validateDate}],
				},
				images: [],
				productId: 0,
				typeJson: [
					{value: 0,label: '依次递减'},
					{value: 1,label: '依次递增'}
				],
			}
		},
		watch: {
			images(val) {
				console.log(val);
				if (val && val.length) {
					this.postForm.images = val.map(item => {
						return item.url
					}).join(',');
				} else {
					this.postForm.images = '';
				}
			},
			categoryId(val) {
				this.$set(this.postForm, `categoryId`, this.$refs['categoryId'].getIds(val))
			}
		},
		created() {
			this.getCategory();
      
      if(this.userInfo.type ===1){
        this.$set(this.postForm, `type`, 0)
      } else {
        this.$set(this.postForm, `type`, 1)
      }
		},
		methods: {
			/*锚链接跳转*/
			anchor(anchorName) {
				/*找到锚点*/
				let anchorElement = document.getElementById(anchorName);
				/*如果对应id的锚点存在，就跳转到锚点*/
				if (anchorElement) {
					//behavior定义动画过渡效果， "auto"或 "smooth" 之一。默认为 "auto"
					anchorElement.scrollIntoView({
						behavior: "smooth"
					});
				}
			},
			selectAddressDetail(value) {
				if (value) {
					this.$set(this.postForm, `startProvinceId`, value.provinceId)
					this.$set(this.postForm, `startProvinceName`, value.provinceName)
					this.$set(this.postForm, `startCityId`, value.cityId)
					this.$set(this.postForm, `startCityName`, value.cityName)
					this.$set(this.postForm, `startDistrictId`, value.districtId)
					this.$set(this.postForm, `startDistrictName`, value.districtName)
				} else {
					this.$set(this.postForm, `startProvinceId`, '')
					this.$set(this.postForm, `startProvinceName`, '')
					this.$set(this.postForm, `startCityId`, '')
					this.$set(this.postForm, `startCityName`, '')
					this.$set(this.postForm, `startDistrictId`, '')
					this.$set(this.postForm, `startDistrictName`, '')
				}
			},
			getCategory() {
				categoryPageVoByQo().then((res) => {
          // let array = [];
          // res.forEach(function(item, index) {
          // 	let data = {};
          // 	data.name = item.name;
          // 	data.id = item.id;
          //   array.push(data);
          // });
          // this.$set(this, 'categoryData', array || [])

					this.$set(this, 'categoryData', res || [])
				})
			},
			submitForm() {
				this.$refs['postForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						biddingSave(this.postForm).then(() => {
							this.loading = false
							// this.$notify({
							// 	title: '成功',
							// 	message: `发布成功`,
							// 	type: 'success',
							// 	duration: 2000
							// })
							
							this.$message({
								message: '发布成功',
								type: 'success'
							});
							this.$router.push('/transaction/biddingBuying')
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "~@/styles/mixin.scss";

	.createPost-container {
		position: relative;

		.createPost-main-container {
			padding: 40px 45px 20px 50px;

			.postInfo-container {
				position: relative;
				@include clearfix;
				margin-bottom: 10px;

				.postInfo-container-item {
					float: left;
					margin-right: 20px;
				}
			}
		}

		.word-counter {
			width: 40px;
			position: absolute;
			right: 10px;
			top: 0px;
		}
	}

	.toInfo {
		position: fixed;
		right: 5px;
		bottom: 40vh;
		// border: 1px solid #eee;
		border-radius: 2px;
		box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
		background: rgba(255, 255, 255, 0.5);

		a {
			display: block;
			padding: 10px;
			border-bottom: 1px solid #eee;

			&:last-child {
				border: none;
			}
		}
	}

	.article-textarea ::v-deep {
		textarea {
			padding-right: 40px;
			resize: none;
			border: none;
			border-radius: 0px;
			border-bottom: 1px solid #bfcbd9;
		}
	}

	.box-card {
		margin-bottom: 30px;

		.flexItem {
			display: flex;
			align-items: center;

			.fuhao {
				margin-right: 3px;
				font-size: 16px;
				color: red;
			}

			.el-input {
				width: auto;
				flex: 1;
			}
		}
	}
</style>
